//
//  FocusTaskManager.swift
//  CatPomodoroTimer
//
//  Created by Xuri Li on 2024/8/28.
//

import Foundation
import SQLite

struct FocusTaskManager {
    
    // insert task
    static func insert(task: FocusTask) throws -> FocusTask {
        guard let db = DatabaseManager.shared.db else {
            throw NSError(domain: "DatabaseError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Database connection not available"])
        }
        
        do {
            return try FocusTask.insert(db: db, task: task)
        } catch {
            throw NSError(domain: "InsertError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Failed to insert task"])
        }
    }
    
    static func update(task: FocusTask) throws {
        guard let db = DatabaseManager.shared.db else {
            throw NSError(domain: "DatabaseError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Database connection not available"])
        }
        
        do {
            try FocusTask.update(db: db, task: task)
        } catch {
            throw NSError(domain: "UpdateError", code: 4, userInfo: [NSLocalizedDescriptionKey: "Failed to update task"])
        }
    }
    
    // fetch completed tasks for today count
    static func fetchCompletedTasksForTodayCount() throws -> Int {
        guard let db = DatabaseManager.shared.db else {
            throw NSError(domain: "DatabaseError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Database connection not available"])
        }
        
        do {
            let completedTasks = try FocusTask.fetchTasksForToday(db: db, completedOnly: true)
            return completedTasks.count
        } catch {
            throw NSError(domain: "FetchError", code: 3, userInfo: [NSLocalizedDescriptionKey: "Failed to fetch completed tasks for today"])
        }
    }
}
